<?php

namespace SGBD\Controller;

class ClubsController extends \SGBD\AbstractController
{
    public function indexAction()
    {
        $saison = $this->getSaisonParam();

        $clubs = $this->db->getAllClubs('Nom_Club', $saison);
        $this->app->render(
            'info/clubs/index.html',
            array('clubs' => $clubs, 'activeSaison' => $saison)
        );
    }

    public function newAction()
    {
        $personnes = $this->db->getAllPersonnesLibre('Nom, Prenom');
        $this->app->render(
            'info/clubs/create.html',
            array('personnes' => $personnes)
        );
    }

    public function viewAction($nomClub)
    {
        $club = $this->db->getClub($nomClub);
        $bureau = $this->db->getBureauClub($nomClub);
        foreach ($bureau as &$b) {
            $b['_href'] = $this->app->urlFor(
                'personne_view', array('numero_personne' => $b['Numero_Personne'])
            );
        }

        $equipes = $this->db->getAllEquipesDeClub($nomClub);
        foreach ($equipes as &$e) {
            $e['_href'] = $this->app->urlFor(
                'equipe_view', array('numero_equipe' => $e['Numero_Equipe'])
            );
        }

        $this->app->render(
            'info/clubs/view.html',
            array('club' => $club, 'bureau' => $bureau, 'equipes' => $equipes)
        );
    }

    public function createAction()
    {
        // TODO: validation!
        //  * Nom de club, longeur
        //  * Nom de adherent, longeur
        //  * Role de adherent, longuer
        //  * Une personne ne peut pas etre membre en plusiers clubs

        try {
            $post = $this->app->request()->post();

            $this->db->beginTransaction();
            $club = $this->db->createClub($post['Nom_Club']);

            if (isset($post['adherent'])) {
                foreach ($post['adherent'] as $adherent) {
                    if ($adherent['type'] === 'nouvelle') {
                        $num = $this->db->createPersonne(
                            $adherent['nom'], '', '', ''
                        );
                    } else if ($adherent['type'] == 'existante') {
                        $num = $adherent['numero_personne'];
                    } else {
                        throw new \SGBD\UnexpectedInputException(
                            'type', $adherent['type']
                        );
                    }
                    $this->db->createAdhesion($club, $num,$adherent['role']);
                }
            }
            $this->db->commit();
        } catch (Exception $e) {
            $this->db->rollback();
            throw $e;
        }

        // Si tout va bien...
        $this->app->redirect($this->app->urlFor('clubs_index'));
    }

    public function editAction($nomClub)
    {
        $club = $this->db->getClub($nomClub);
        $bureau = $this->db->getBureauClub($nomClub);
        $bureauJson = json_encode($bureau);
        $personnes = $this->db->getAllPersonnesLibre('Nom, Prenom');
        $this->app->render(
            'info/clubs/create.html',
            array(
                'personnes' => $personnes,
                'club' => $club,
                'bureauJson' => $bureauJson
            )
        );
    }


    public function updateAction($nomClub)
    {
        $post = $this->app->request()->post();
        $club = $this->db->getClub($nomClub);
        $bureau = $this->db->getBureauClub($nomClub);

        // Ajoute des nouvelles personnes
        foreach ($post['adherent'] as &$adherent) {
            if ($adherent['type'] === 'nouvelle') {
                $pnum = $this->db->createPersonne($adherent['nom']);
                $adherent['numero_personne'] = $pnum;
            }
        }

        $bureauParPNum = rekey($bureau, 'Numero_Personne');
        $newBureauParPNum = rekey($post['adherent'], 'numero_personne');

        // Must handle: new posts, deleted posts, updated posts
        foreach ($post['adherent'] as $adherent) {
            // If the posted adherent is not in the bureau, or if she is there
            // but with another role, delete adhesion and create a new one.
            $pnum = $adherent['numero_personne'];
            $role = $adherent['role'];
            if (!isset($bureauParPNum[$pnum])) {
                // New
                $this->db->createAdhesion($nomClub, $pnum, $role);
            } else if ($bureauParPNum[$pnum]['Role'] != $role) {
                // Modified
                $this->db->deleteAdhesion($pnum);
                $this->db->createAdhesion($nomClub, $pnum, $role);
            } // else nothing changed to this member
        }

        // Now loop over the bureau and see if something needs to be deleted!
        foreach ($bureau as $adherent) {
            $pnum = $adherent['Numero_Personne'];
            if (!isset($newBureauParPNum[$pnum])) {
                $this->db->deleteAdhesion($pnum);
            }
        }

        // Si tout va bien...
        $url = $this->app->urlFor('club_view', array('nom_club' => $nomClub));
        $this->app->redirect($url);
    }


    public function deleteAction($nomClub)
    {
        $this->db->deleteClub($nomClub);
        $this->app->redirect($this->app->urlFor('clubs_index'));
    }
}